import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  Badge,
  Divider,
  Radio,
  Dropdown,
  Menu,
  Popconfirm,
  Icon,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {ruleP, nameMaxLength,remarkMaxLength,contentLength} from '@/utils/rule'
import styles from '../search.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');

const matchTypeValue = ['关键字', '正则表达式'];
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const CreateForm = Form.create()(props => {

  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible ,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title="新增敏感字段"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="字段名称">
        {form.getFieldDecorator('name', {
          rules: [{required: true,message:'字段名称不能为空'},{max:nameMaxLength()[0],message:nameMaxLength()[1]}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="匹配类型">
        {form.getFieldDecorator('matchType', {
          rules: [{required: true,message:'请选择匹配类型'}],initialValue:"0"
        })(
          <Radio.Group>
            <Radio value="0">
              关键字
            </Radio>
            <Radio value="1">
              正则表达式
            </Radio>
          </Radio.Group>
        )}
      </FormItem>

      <FormItem {...formLayout} label="敏感内容">
        {form.getFieldDecorator('sensitiveContent', {
          rules: [{required: true,message:'敏感内容不能为空'},{max:contentLength()[0],message:contentLength()[1]}],
        })(<TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={3}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="备注">
        {form.getFieldDecorator('remark',{rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}]})(<TextArea
          style={{minHeight: 32}}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        name: props.values.name,
        sensitiveContent: props.values.sensitiveContent,
        matchType: props.values.matchType,
        remark: props.values.remark,
        status: props.values.status,
        wordId: props.values.wordId,
      },
    };
  }

  //编辑，确定提交
  handleCheck = checkBtn => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          handleUpdate(formVals);
        }

      );
    });
  };
  renderFooter = checkBtn => {
    const { handleUpdateModalVisible, values } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleCheck(checkBtn)}>
        确定
      </Button>,
    ];
  };


  render() {
    const { updateModalVisible, handleUpdateModalVisible, values ,form
    } = this.props;
    const { checkBtn, formVals } = this.state;
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="编辑敏感字段"
        visible={updateModalVisible}
        footer={this.renderFooter(checkBtn)}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
        maskClosable={false}
      >

        <FormItem id="name" {...formLayout} label="字段名称">
          {form.getFieldDecorator('name', {
            rules: [{required: true,message:'字段名称不能为空'}],initialValue: formVals.name
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem id="matchType" {...formLayout} label="匹配类型">
          {form.getFieldDecorator('matchType',{rules: [{required: true,message:'请选择匹配类型'}],initialValue: formVals.matchType.toString()})(
            <Radio.Group>
              <Radio value="0">
                关键字
              </Radio>
              <Radio value="1">
                正则表达式
              </Radio>
            </Radio.Group>
          )}
        </FormItem>

        <FormItem id="sensitiveContent" {...formLayout} label="敏感内容">
          {form.getFieldDecorator('sensitiveContent', {
            rules: [{required: true,message:'敏感内容不能为空'}],initialValue: formVals.sensitiveContent
          })(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>

        <FormItem id="remark" {...formLayout} label="备注">
          {form.getFieldDecorator('remark', {
            initialValue: formVals.remark
          })(<TextArea
            style={{minHeight: 32}}
            rows={2}
          />)}
        </FormItem>

        <FormItem id="status" {...formLayout} label="状态设置">
          {form.getFieldDecorator('status',{initialValue: formVals.status.toString()})(
            <Radio.Group>
              <Radio value="0">
                启用
              </Radio>
              <Radio value="1">
                禁用
              </Radio>
            </Radio.Group>
          )}
        </FormItem>

      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ keyword, loading }) => ({
  keyword,
  loading: loading.models.keyword,
}))
@Form.create()
class keyword extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };


  columns = [
    {
      title: '敏感字段名称',
      dataIndex: 'name',
    },
    {
      title: '匹配类型',
      dataIndex: 'matchType',
      render(val) {
         return matchTypeValue[val];
       }
    },
    {
      title: '敏感内容',
      dataIndex: 'sensitiveContent',
      width:'40%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },

    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, record)}>详情</a>          
          <Divider type="vertical" />
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.wordId)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'keyword/queryList',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, id) => {
      const newObj = { ...obj };
      newObj[id] = getValue(filtersArg[id]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'keyword/queryList',
      payload: params,
    });
  };

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  handleThisRowDelete = (wordId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'keyword/remove',
      payload: {wordId},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'keyword/queryList',});
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

//批量删除
  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.wordId;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'keyword/queryList',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      editFormValues: record || {},
    });
  };

  handleDetailModalVisible = (flag,text) => {
    this.setState({
      detailModalVisible: !!flag,
      detailsData: text,
    });
  };


  //新增
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'keyword/add',
      payload: {
        name: fields.name,
        sensitiveContent: fields.sensitiveContent,
        matchType: fields.matchType,
        remark: fields.remark,
      },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'keyword/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
    this.handleModalVisible();
  };

  //编辑
  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'keyword/update',
      payload: {
        /*query: formValues,*/
          name: fields.name,
          sensitiveContent: fields.sensitiveContent,
          matchType: fields.matchType,
          remark: fields.remark,
          status: fields.status,
          wordId: fields.wordId,
      },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'keyword/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });

    this.handleUpdateModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="敏感字段名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      keyword: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, editFormValues,detailModalVisible, detailsData } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    return (
      <PageHeaderWrapper title="敏感字段">
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.wordId}
          />
        </div>
        {editFormValues && Object.keys(editFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={editFormValues}
          />
        ) : null}

        {detailsData&&detailsData.wordId?(
          <Details {...detailsMethods} detailModalVisible={detailModalVisible} detailsData={detailsData} />
        ):null}


      </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible,detailsData } = this.props;
    return (
      <Modal
        destroyOnClose
        width={640}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
    <Row>
      <Col md={24}>
        <FormItem id="name" {...formLayout} label="字段名称">
          {detailsData.name}
        </FormItem>
      </Col>

      <Col md={24}>
        <FormItem id="matchType" {...formLayout} label="匹配类型">
          {matchTypeValue[detailsData.matchType]}
        </FormItem>
      </Col>

      <Col md={24}>
        <FormItem id="matchType" {...formLayout} label="敏感内容">
          {detailsData.sensitiveContent}
        </FormItem>
      </Col>

      <Col md={24}>
        <FormItem id="matchType" {...formLayout} label="备注">
          {detailsData.remark}
        </FormItem>
      </Col>

      <Col md={24}>
        <FormItem id="matchType" {...formLayout} label="状态">
          {status[detailsData.status]}
        </FormItem>
      </Col>
    </Row>

      </Modal>
    );
  }
}

export default keyword;
